import logging
from pymongo.errors import PyMongoError
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase

MONGO_URL="mongodb://localhost:27017"
MONGO_DATABASE="dwf_ai"

client: AsyncIOMotorClient | None = None
db: AsyncIOMotorDatabase | None = None

log = logging.getLogger("uvicorn.error")


async def connect_to_mongo():
    """在应用启动时建立数据库连接"""
    global client, db
    log.info(f"Connecting to MongoDB: {MONGO_URL}")
    try:
        client = AsyncIOMotorClient(MONGO_URL)
        await client.admin.command("ping")  # 强制连接
        db = client[MONGO_DATABASE]
        log.info("Successfully connected to MongoDB!")
    except PyMongoError as e:
        log.error(f"Failed to connect to MongoDB: {e}")
        raise RuntimeError("MongoDB connection failed") from e


async def close_mongo_connection():
    """在应用关闭时断开数据库连接"""
    global client
    if client:
        client.close()
        log.info("MongoDB connection closed.")


def get_database() -> AsyncIOMotorDatabase:
    """获取数据库实例的依赖项"""
    if db is None:
        raise Exception("Database not initialized. Call connect_to_mongo first.")
    return db


